/**
 * 评论media框 行内使用
 */

import React from 'react';
import { Tag, Balloon, Checkbox } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import MarkdownIt from 'markdown-it';
import hljs from 'utils/hl.js';
import MdEditor from 'components/mdEditor';
import utils from 'utils';
import './inlineComment.scss';
import LineInfo from './lineInfo';
import { ENUM } from 'utils/constants';
import milt from 'markdown-it-link-target';
import { filterXSS } from 'xss';
import track from 'utils/track';
import intl from '../../../../../../../../../../../locale';

const { ctrlTxt } = ENUM.getOSKeyMap();

const md = new MarkdownIt({
  html: true,
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value;
      } catch (__) {
        return '';
      }
    }

    return ''; // 使用额外的默认转义
  },
}).use(milt, {
  target: '_blank',
});

const { pathResource } = window.FORCE;

export default class CommentMedia extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isEditing: false,
      isHover: false, // 是否悬浮
    };
    this.mediaRef = React.createRef();
  }

  onCancelEditing = () => {
    this.setState({
      isEditing: false,
    });
  };

  renderExtraInfo = () => {
    const { comment, notMatched, changesReducer, mrCommentConfig } = this.props;
    const { allComments = [] } = changesReducer;
    const hasPermission =
      pathResource.isArchive === 'false' &&
      utils.allowComments(allComments.length, mrCommentConfig);
    const { created_at: createdAt, is_draft } = comment;
    if (is_draft) {
      return (
        <span className="comment-draft">
          <Tag color="orange">
            {intl.get({
              id: 'code-assets.components.commentMedia.inlineComment.Draft',
              defaultMessage: '草稿',
            })}
          </Tag>
        </span>
      );
    }

    const isShowReplyBtn = hasPermission && !notMatched && this.state.isHover;
    return (
      <React.Fragment>
        <span className="comment-time"> · {utils.getBeautyTime(createdAt)}</span>
        {isShowReplyBtn && (
          <a
            onClick={(e) => {
              e.stopPropagation();
              this.props.replyFn && this.props.replyFn(comment);
            }}
            className="reply-btn"
          >
            {intl.get({
              id: 'code-assets.components.commentMedia.inlineComment.Response',
              defaultMessage: '回复',
            })}
          </a>
        )}
      </React.Fragment>
    );
  };

  onSubmit = (value) => {
    const { comment } = this.props;
    const { id } = comment;
    this.props.updateDraft({
      noteId: id,
      note: value,
    });

    this.onCancelEditing();
  };

  render() {
    const { changesReducer, mrCommentConfig, comment, useInLog, codeReviewDetail } = this.props;
    const { allComments = [] } = changesReducer;
    const hasPermission =
      pathResource.isArchive === 'false' &&
      utils.allowComments(allComments.length, mrCommentConfig);
    const { note: content, id, is_draft } = comment;
    // 编辑删除自己的评论 暂不支持
    // const isSelfComment = Number(author.id) === Number(window.FORCE.user.codeUserId);

    if (!comment) {
      return null;
    }
    return (
      <div
        className="comment-new-media"
        onMouseEnter={() => {
          this.setState({
            isHover: true,
          });
        }}
        onMouseLeave={() => {
          this.setState({
            isHover: false,
          });
        }}
        ref={this.mediaRef}
      >
        <div className="comment-new-media-title">
          <div className="comment-new-media-title-left">
            <Balloon.Tooltip
              align="t"
              trigger={
                <div className="user-name one-line-ellipsis">
                  {(comment.author && comment.author.name) || ''}
                </div>
              }
              text={(comment.author && comment.author.name) || ''}
            />

            <div className="time-reply">{this.renderExtraInfo()}</div>
          </div>
          {hasPermission && !useInLog && is_draft ? (
            <div className="comment-new-media-title-right">
              <Balloon.Tooltip
                align="t"
                trigger={
                  <ButtonIcon
                    name="edit-line"
                    className="comment-title-btn"
                    onClick={() => {
                      this.setState({
                        isEditing: true,
                      });

                      track({
                        action: 're_edit_draft',
                        page: ':Repo-MR-changes',
                        type: '',
                        mr_id: codeReviewDetail.id,
                      });
                    }}
                  />
                }
                text={intl.get({
                  id: 'code-assets.components.commentMedia.inlineComment.Editing',
                  defaultMessage: '编辑',
                })}
              />

              <Balloon.Tooltip
                align="t"
                trigger={
                  <ButtonIcon
                    name="delete-line"
                    className="comment-title-btn"
                    onClick={() => {
                      this.props.deleteDraft(id);
                      track({
                        action: 'delete_draft',
                        page: ':Repo-MR-changes',
                        type: '',
                        mr_id: codeReviewDetail.id,
                      });
                    }}
                  />
                }
                text={intl.get({
                  id: 'code-assets.components.commentMedia.inlineComment.Delete',
                  defaultMessage: '删除',
                })}
              />
            </div>
          ) : null}
          {/* TODO: 接口还没解决状态，暂时不加 */}
          {hasPermission && !useInLog && !is_draft && !comment.parent_note_id ? (
            <div className="comment-new-media-title-right">
              <Balloon.Tooltip
                trigger={
                  <div className={'comment-close-btn'}>
                    <Checkbox
                      onClick={() => {
                        this.props.toggleComment({ noteId: comment.id, closed: !comment.closed });
                      }}
                      checked={!!comment.closed}
                    >
                      {comment.closed
                        ? intl.get({
                            id: 'code-assets.components.commentMedia.inlineComment.Resolved',
                            defaultMessage: '已解决',
                          })
                        : intl.get({
                            id: 'code-assets.components.commentMedia.inlineComment.ToBeResolved',
                            defaultMessage: '待解决',
                          })}
                    </Checkbox>
                  </div>
                }
                onClick={this.props}
                align="t"
              >
                {comment.closed
                  ? intl.get({
                      id: 'code-assets.components.commentMedia.inlineComment.MarkAsPending',
                      defaultMessage: '标记为待解决',
                    })
                  : intl.get({
                      id: 'code-assets.components.commentMedia.inlineComment.MarkAsResolved',
                      defaultMessage: '标记为已解决',
                    })}
              </Balloon.Tooltip>
            </div>
          ) : null}
        </div>
        <div className="comment-new-media-body">
          {useInLog && <LineInfo comment={comment} />}
          {!this.state.isEditing ? (
            <div
              className="comment-content markdown-body"
              dangerouslySetInnerHTML={{
                __html: filterXSS(md.render(content || ''), {
                  onIgnoreTagAttr: (_, name, value) => {
                    return `${name}=${value}`;
                  },
                }),
              }}
            />
          ) : (
            <MdEditor
              initValue={content || ''}
              size="small"
              onSubmit={this.onSubmit}
              onCancel={this.onCancelEditing}
              placeholder={intl.get({
                id: 'code-assets.components.commentMedia.inlineComment.EnterAComment',
                defaultMessage: '请输入评论',
              })}
              help={intl.get(
                {
                  id: 'code-assets.components.commentMedia.inlineComment.CtrltxtEnterTheUpdateDraft',
                  defaultMessage: '{ctrlTxt} + Enter 更新草稿',
                },
                { ctrlTxt },
              )}
              submitBtnText={intl.get({
                id: 'code-assets.components.commentMedia.inlineComment.UpdateDraft',
                defaultMessage: '更新草稿',
              })}
              ref={(ref) => {
                this.mdRef = ref;
              }}
            />
          )}
        </div>
      </div>
    );
  }
}
